package org.ubc.cs410.disposal2020.client;

import org.ubc.cs410.disposal2020.Game;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/*
 * when user started a new game he/she has to wait for another player to join
 */

public class GameHostWaiting implements EntryPoint {

	private GameServiceAsync gameService;
	private Timer timer;

	@Override
	public void onModuleLoad() {
		init();

		initTimer();

		VerticalPanel mainPanel = new VerticalPanel();

		RootPanel.get("waiting").add(mainPanel);
	}

	private void initTimer() {
		timer = new Timer() {
			@Override
			public void run() {
				gameService.isGameReady(new AsyncCallback<String>() {

					@Override
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(String result) {
						if (result != null) {
							timer.cancel();
							redirect("/game/" + result);
						}
					}
				});

			}
		};
		timer.scheduleRepeating(1000);

	}

	private void init() {
		gameService = (GameServiceAsync) GWT.create(GameService.class);
		ServiceDefTarget endpoint = (ServiceDefTarget) gameService;
		endpoint.setServiceEntryPoint("/services/game");
	}

	native void redirect(String url)
	/*-{
		$wnd.location.replace(url);
	}-*/;

}
